package com.haoshuang.zhouzhoubang.ui.activity

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.res.AssetManager
import android.location.LocationManager
import android.media.MediaPlayer
import android.net.Uri
import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.haoshuang.zhouzhoubang.R
import com.haoshuang.zhouzhoubang.databinding.ActivityComfirmDoorInBinding
import com.haoshuang.zhouzhoubang.databinding.ItemServiceItemWithimgBinding
import com.haoshuang.zhouzhoubang.model.bean.OrderBean5
import com.haoshuang.zhouzhoubang.model.bean.OrderDetail2Bean
import com.haoshuang.zhouzhoubang.model.bean.OrderGoodsBean
import com.haoshuang.zhouzhoubang.model.bean.PriceBean
import com.haoshuang.zhouzhoubang.ui.dialog.CallDialog
import com.haoshuang.zhouzhoubang.ui.dialog.ConfirmDialog
import com.haoshuang.zhouzhoubang.ui.dialog.ShowUploadExampleDialog
import com.haoshuang.zhouzhoubang.ui.dialog.Ts9Dialog
import com.haoshuang.zhouzhoubang.ui.dialog.UploadWriteOffCodeDialog
import com.haoshuang.zhouzhoubang.ui.page.order.receiveorder.detail.ServiceItemAdapter
import com.haoshuang.zhouzhoubang.ui.vm.ComfirmDoorInViewModel
import com.haoshuang.zhouzhoubang.utils.ChooseMediaUtils
import com.haoshuang.zhouzhoubang.utils.OSSUploadUtils
import com.haoshuang.zhouzhoubang.widget.UploadFileBean
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lnkj.jialubao.utils.AccountUtils
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.lxj.xpopup.XPopup
import com.mufeng.libs.base.BaseBindingHolder
import com.mufeng.libs.base.BaseBindingQuickAdapter
import com.mufeng.libs.base.BaseVMActivity
import com.mufeng.libs.state.observeState
import com.mufeng.libs.utils.SpannableStringUtils
import com.mufeng.libs.utils.startPageForResult
import com.mufeng.libs.utils.toast
import com.mufeng.libs.utils.view.click
import com.mufeng.libs.utils.view.clickWithTrigger
import com.mufeng.libs.utils.view.gone
import com.mufeng.libs.utils.view.load
import com.mufeng.libs.utils.view.visible
import com.mufeng.libs.utils.view.visibleOrGone
import java.io.IOException

/**
 *  确认上门界面
 */
class ComfirmDoorInActivity :
    BaseVMActivity<ComfirmDoorInViewModel, ActivityComfirmDoorInBinding>() {

    private var orderDetailBean: OrderDetail2Bean? = null
    private var orderBean5: OrderBean5? = null

    private var is_rework = false

    var type9 = 0

    @SuppressLint("MissingPermission")
    override fun initView(savedInstanceState: Bundle?) {

        is_rework = intent.getBooleanExtra("is_rework", false)
        /*  val tvDoorPhotoStr = SpannableStringUtils(this, "上传服务前照片（至少4张） *")
              .first("*").textColor(R.color.c_ff0000)*/

        binding.apply {

            tvUploadExample.clickWithTrigger {
                // 查看上传示例
                // 后期需要先请求接口
                XPopup.Builder(mActivity)
                    .asCustom(
                        ShowUploadExampleDialog(
                            context = mActivity,
                            order_id = ids.toString()
                        )
                    )
                    .show()
            }

            appBar.ivBack.clickWithTrigger { finish() }
            appBar.tvTitle.text = "确认服务"
            appBar.tvRight.clickWithTrigger {
                showUploadWriteOffCodeDialog()
            }
            ivServiceCustom.clickWithTrigger {
                // 联系客服
                val myBean = AccountUtils.user
                XPopup.Builder(mActivity)
                    .asCustom(CallDialog(mActivity, myBean?.master_customer_tel ?: "") {
                        val intent = Intent(Intent.ACTION_DIAL);
                        intent.setData(Uri.parse("tel:${myBean?.master_customer_tel ?: ""}"));
                        startActivity(intent);
                    })
                    .show()
            }
            tXz.clickWithTrigger {
                if (type9 == 0) {
                    type9 = 1
                    tXz.setImageResource(R.mipmap.icon_xl2)
                    ivImage.visible()
                } else {
                    type9 = 0
                    ivImage.gone()
                    tXz.setImageResource(R.mipmap.icon_xl)
                }
            }
//            tvDoorPhoto.text = tvDoorPhotoStr

            llExtraCosts.setOnClickListener {
                startPageForResult<SetExtraCostsActivity>(
                    "order_id" to ids,
                    "type" to 0,
                    "cost_status" to cost_status,
                    "cost_name" to cost_name,
                    "money" to money,
                    "cost_img" to cost_img,
                    "cost_remark" to cost_remark,
                    "cost_id" to cost_id
                ) { code, data ->
                    if (code == 978) {
                        if (data != null) {
                            cost_name = data.getStringExtra("cost_name").toString()
                            money = data.getStringExtra("money").toString()
                            cost_img = data.getStringExtra("cost_img").toString()
                            cost_remark = data.getStringExtra("cost_remark").toString()
                            cost_status = 2
                            is_cost = "1"
                            binding.tvFy.text = "¥$money"
                        }
                    } else if (code == 998) {
                        if (data != null) {
                            cost_name = data.getStringExtra("cost_name").toString()
                            money = data.getStringExtra("money").toString()
                            cost_id = data.getIntExtra("cost_id", 0).toString()
                            cost_img = data.getStringExtra("cost_img").toString()
                            cost_status = 1
                            is_cost = "1"
                            binding.tvFy.text = "¥$money"
                        }
                    }
                }
            }

            tvStartService.setOnClickListener {
                val imageList = rvDropInPast.getMediaList().filter { !it.isVideo }
                val video = rvDropInPast.getMediaList().filter { it.isVideo }
                val warkClothesImageList = rvWorkClothes.getMediaList()
                /*if (imageList.isEmpty()) {
                    toast("请选择上门前照片")
                    return@setOnClickListener
                }*/
                /*if (imageList.size < 4) {
                    toast("最少4张")
                    return@setOnClickListener
                }*/
                if (orderBean5?.image_gongzhuang_show != 0) {
                    if (is_clothes == "1" && warkClothesImageList.isEmpty()) {
                        toast("工装照最少1张")
                        return@setOnClickListener
                    }
                }

                commit()
            }

        }

        // 点击查看奖励
        binding.ivUploadReward.clickWithTrigger {
            XPopup.Builder(this)
                .asCustom(
                    ConfirmDialog(
                        context = this,
                        title = "上传视频奖励",
                        content = "需上传服务前服务后视频有${orderBean5?.upload_video_award ?: "0"}元上传奖励",
                        cancelStr = "",
                        confirmStr = "我知道了",
                        isHideCancel = true,
                        onCancel = {},
                        onConfirm = {})
                )
                .show()
        }
    }

    private var imageList22 = arrayListOf<LocalMedia>()
    var cost_status = 2//1选择2填写
    var cost_name = ""//1选择2填写
    var money = ""//1选择2填写

    lateinit var mLocationManager: LocationManager
    var ids = 0

    @SuppressLint("MissingPermission")
    override fun initData() {
        ids = intent.getIntExtra("ids", 0)
        vm.getData55("id" to ids)
        vm.getData5("id" to ids)
        vm.getData2("id" to ids)
        // 获取订单详情
        vm.getOrderDetail("id" to ids)
        mLocationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager // 位置
    }


    var list55 = arrayListOf<PriceBean>()
    var is_clothes = "0"
    override fun startObserve() {

        vm.getOrderDetailData.observeState(this) {
            onSuccess {
                orderDetailBean = it

                if (orderDetailBean?.is_cart_order == 1) {
                    binding?.layoutServiceItem?.visibility = View.VISIBLE
                    binding?.layoutServiceItemOld?.visibility = View.GONE

                    var serviceItemAdapter: ServiceItemWithImgAdapter?
                    if (orderDetailBean?.order_goods?.size!! > 2) {
                        serviceItemAdapter =
                            ServiceItemWithImgAdapter(orderDetailBean?.order_goods!!.subList(0, 2))
                        binding?.layoutLookmore?.visibility = View.VISIBLE
                    } else {
                        serviceItemAdapter = ServiceItemWithImgAdapter(orderDetailBean?.order_goods!!)
                        binding?.layoutLookmore?.visibility = View.GONE
                    }
                    binding?.recyclerViewSeriviceItem?.layoutManager = LinearLayoutManager(
                        this@ComfirmDoorInActivity,
                        LinearLayoutManager.VERTICAL, false
                    )
                    binding?.recyclerViewSeriviceItem?.adapter = serviceItemAdapter
                    binding?.layoutLookmore?.click {
                        serviceItemAdapter.submitList(orderDetailBean?.order_goods!!)
                        binding?.layoutLookmore?.visibility = View.GONE
                    }

                } else {
                    binding?.layoutServiceItem?.visibility = View.GONE
                    binding?.layoutServiceItemOld?.visibility = View.VISIBLE
                }

                val tvDoorPhotoStr = SpannableStringUtils(
                    this@ComfirmDoorInActivity,
                    "上传服务前照片（至少" + orderDetailBean?.image_qian_count + "张） *"
                )
                    .first("*").textColor(R.color.c_ff0000)
                binding.tvDoorPhoto.text = tvDoorPhotoStr
            }
        }

        vm.uploadWriteOffCodeData.observeState(this) {
            onLoading { }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                toast("核销码上传成功, 等待核销")
            }
        }

        vm.getData5.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                orderBean5 = it
                binding.apply {
                    ivHead.load(it?.image)
                    ivImage.load(it?.service_con_image, R.mipmap.default_image)
                    tvName.text = it?.store_name
                    tvMaij.text = it?.suk_unique
                    is_clothes = it?.is_clothes.toString()
                    if (it?.is_clothes == "0") {
                        tvWorkClothes.text = "请上传工装照片"
                    } else {
                        val tvDoorPhotoStr = SpannableStringUtils(
                            this@ComfirmDoorInActivity,
                            "请上传工装照片（至少1张） *"
                        )
                            .first("*").textColor(R.color.c_ff0000)
                        tvWorkClothes.text = tvDoorPhotoStr
                    }

                    // 回显工具照片
                    if (it?.tool_pictures?.isNotEmpty() == true) {
                        val list = it.tool_pictures.split(",")

                        val warkPastImageList = arrayListOf<UploadFileBean>()
                        for (str in list) {
                            warkPastImageList.add(UploadFileBean(null, str, 0, false, 2))
                        }
                        binding.rvWorkPast.setMediaList(warkPastImageList)
                    }

                    // 上传核销码
                    binding.appBar.tvRight.visibleOrGone(it?.is_write_off == 1)
                    binding.appBar.tvRight.text = "上传核销码"
                    if (it?.is_write_off == 1) {
                        showUploadWriteOffCodeDialog()
                    }
                }

                if (orderBean5?.image_qian_show == 0) {
                    binding?.layoutFuwuqian?.visibility = View.GONE
                } else {
                    binding?.layoutFuwuqian?.visibility = View.VISIBLE
                }

                if (orderBean5?.image_gongju_show == 0) {
                    binding?.layoutGongju?.visibility = View.GONE
                } else {
                    binding?.layoutGongju?.visibility = View.VISIBLE
                }
                if (orderBean5?.image_gongzhuang_show == 0) {
                    binding?.layoutGongzhuang?.visibility = View.GONE
                } else {
                    binding?.layoutGongzhuang?.visibility = View.VISIBLE
                }
            }
        }
        vm.getData55.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                if (code != "402") {
                    toast(msg)
                }
            }
            onSuccess {
                dismissLoading()
                if (it != null)
                    list55 = it
            }
        }
        vm.getData2.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                if (it?.size!! > 0) {
                    cost_status = 1
                } else {
                    cost_status = 2
                }
            }
        }
        vm.getData.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                toast("您已确认服务")
                if (!is_rework) {
                    LiveEventBus.get<Boolean>("Sxx").post(true)
                    LiveEventBus.get<Boolean>("Sxx3").post(true)
                    // 判断播放音乐
                    if (orderDetailBean?.is_team == "1") {
                        val player = MediaPlayer()
                        val assetManager: AssetManager = resources.assets
                        try {
                            val fileDescriptor = assetManager.openFd("confirm_doorin_tip.mp3")
                            player.setDataSource(
                                fileDescriptor.fileDescriptor,
                                fileDescriptor.startOffset,
                                fileDescriptor.length
                            )
                            player.prepare()
                            player.start()
                        } catch (e: IOException) {
                            e.printStackTrace()
                        }
                    }
                } else {
                    setResult(200)
                }
                finish()
            }
        }
    }

    /**
     * 上传核销码
     */
    private fun showUploadWriteOffCodeDialog() {
        XPopup.Builder(this)
            .dismissOnTouchOutside(false)
            .dismissOnBackPressed(false)
            .asCustom(
                UploadWriteOffCodeDialog(
                    this,
                    "请上传核销码，并在确认上门前\n或服务完成后向用户索要"
                ) {
                    uploadWriteOffCodeImage()
                })
            .show()
    }

    private fun uploadWriteOffCodeImage() {
        ChooseMediaUtils(mActivity).selectSingleImageWithCamera(object :
            OnResultCallbackListener<LocalMedia> {
            override fun onResult(result: java.util.ArrayList<LocalMedia>?) {
                if (result != null && result.size > 0) {
                    OSSUploadUtils.uploadFile("app/upload", result.first().realPath) {
                        start { showLoading() }
                        error { clientException, serviceException ->
                            dismissLoading()
                            toast("图片上传失败")
                        }
                        success {
                            dismissLoading()
                            vm.uploadWriteOffCode(ids.toString(), it)
                        }
                    }
                }
            }

            override fun onCancel() {

            }
        })
    }

    var cost_remark = ""
    var cost_img = ""
    var is_cost = "0"
    var cost_id = ""
    private fun commit() {
        dismissLoading()
        if (money.isEmpty() || money == "0") {
            commit2()
        } else {
            XPopup.Builder(this)
                .asCustom(
                    Ts9Dialog(
                        this
                    ) {
                        commit2()
                    })
                .show()

        }

    }

    private fun commit2() {

        val imageList = binding.rvDropInPast.getMediaList().filter { !it.isVideo }
        val workPastImageList = binding.rvWorkPast.getMediaList()
        val workClothesImageList = binding.rvWorkClothes.getMediaList()

        // 上门前图片地址
        val visit_img = imageList.joinToString(",") { it.url.toString() }
        // 上门前视频地址
        val video = binding.rvDropInPast.getMediaList().firstOrNull { it.isVideo }?.url
        // 工具照片
        val before_work_img = workPastImageList.joinToString(",") { it.url.toString() }
        // 工装照片
        val work_clothes_img = workClothesImageList.joinToString(",") { it.url.toString() }
        var remark = ""
        if (orderDetailBean?.is_cart_order == 1) {
             remark = binding.tvMark.text.toString()
        }else{
            remark = binding.tvMark1.text.toString()
        }


        if (is_cost == "0") {

            vm.getData(
                "id" to ids,
                "visit_img" to visit_img,
                "video" to video,
                "before_work_img" to before_work_img,
                "work_clothes_img" to work_clothes_img,
                "is_cost" to is_cost,
                "remark" to remark
            )
        } else {
            if (cost_status == 1) {
                vm.getData(
                    "id" to ids,
                    "video" to video,
                    "visit_img" to visit_img,
                    "before_work_img" to before_work_img,
                    "work_clothes_img" to work_clothes_img,
                    "money" to money,
                    "cost_remark" to cost_remark,
                    "cost_img" to cost_img,
                    "is_cost" to is_cost,
                    "cost_status" to cost_status,
                    "cost_id" to cost_id,
                    "remark" to remark
                )
            } else {
                vm.getData(
                    "id" to ids,
                    "video" to video,
                    "visit_img" to visit_img,
                    "before_work_img" to before_work_img,
                    "work_clothes_img" to work_clothes_img,
                    "cost_name" to cost_name,
                    "money" to money,
                    "cost_remark" to cost_remark,
                    "cost_img" to cost_img,
                    "is_cost" to is_cost,
                    "cost_status" to cost_status,
                    "remark" to remark
                )
            }

        }
    }
}

class ServiceItemWithImgAdapter(data: MutableList<OrderGoodsBean>) :
    BaseBindingQuickAdapter<OrderGoodsBean, ItemServiceItemWithimgBinding>(data) {

    override fun onBindViewHolder(holder: BaseBindingHolder, position: Int, item: OrderGoodsBean?) {
        val binding = ItemServiceItemWithimgBinding.bind(holder.itemView)
        binding.tvGoodsName.text = item?.goods_name
        binding.tvProductAttrName.text = item?.product_attr_name
        binding.tvNum.text = "x" + item?.num.toString()
        binding.tvMoney.text = "¥" + item?.money
        binding.ivImage.load(item?.image)
    }
}
